import { ref, watch } from "vue";
import { map, uniq } from "lodash";
import { handleWorkloadKey } from "@/utils";
import { getExceptionList } from "@/api/topoNodeDetail";
export default function useExceptionList({
  node:nodeInfo,
  pageType,
  queryTime,
  url,
  type,
  srcNodes,
  allDataExceptCount
}) {
  const {from, to} = queryTime.value
  const exceptionListParams = ref({
    startPage: 1,
    size: 10,
    startTime: from,
    endTime: to,
    isDesc: true,
    orderFiled: "requestTotalTime",
  });
  const exceptionList = ref([]);
  const exceptionLoading = ref(false);
  const exceptionTotal = ref(0)
  const buildExceptionParams = () => {
    // const nodeInfo =
    const node = nodeInfo.value

    if (pageType.value === "node") {
      const params = {
        ...exceptionListParams.value,
        startTime: from,
        endTime: to,
        startPage: 1,
        masterIps: [node.masterIp],
        dstNamespace: node.namespace,
        dstWorkloadName: node.workloadName,
        dstWorkloadKind: node.workloadKind,
        dstPodName: type.value === "pod" ? node.podName : undefined,
      };
      if (srcNodes.length) {
        const extraParams = map(srcNodes.value, (node) => {
          return {
            masterIp: node.masterIp,
            namespace: node.namespace,
            workloadKind: node.workloadKind,
            workloadName: node.workloadName,
            podName: type.value === "pod" ? node.podName : undefined,
          };
        });
        type.value === "pod"
          ? (params.srcPodList = extraParams)
          : (params.srcWorkloadList = extraParams);
      }
      return params;
    } else {
      const {
        masterIp: srcMasterIp,
        namespace: srcNamespace,
        workloadKind: srcWorkloadKind,
        workloadName: srcWorkloadName,
      } = handleWorkloadKey(node.srcWorkloadKey || "");
      const {
        masterIp: dstMasterIp,
        namespace: dstNamespace,
        workloadKind: dstWorkloadKind,
        workloadName: dstWorkloadName,
      } = handleWorkloadKey(node.dstWorkloadKey || "");
      return {
        ...exceptionListParams,
        startTime: from,
        endTime: to,
        startPage: 1,
        masterIps: uniq([srcMasterIp, dstMasterIp]),
        srcWorkloadList: [
          {
            masterIp: srcMasterIp,
            namespace: srcNamespace,
            workloadKind: srcWorkloadKind,
            workloadName: srcWorkloadName,
          },
        ],
        dstNamespace,
        dstWorkloadName,
        dstWorkloadKind,
      };
    }
  };
  // 获取异常请求
  const getExceptionData = (...args) => {
    exceptionLoading.value = true;
    const [params, count] = args;
    // * 全量那边算出来的exceptionCount是trace聚合过的，但是这个接口是不聚合的。要尽可能保证数据一致。
    const data = count ? { ...params, exceptionCount: count } : params;
    getExceptionList(data)
      .then((res) => {
        const { responseEsPageVO } = res.data;
        let total;
        // if(allDataExceptCount.current) {
        //     total =  Math.min(allDataExceptCount.current, responseEsPageVO?.total)
        // }else
        if (count) {
          total = Math.min(count, responseEsPageVO?.total);
        }
        //  else if(allDataExceptCount.current) {
        //     total =  Math.min(allDataExceptCount.current, responseEsPageVO?.total)
        // }
        console.log(total, "total", count);

        exceptionList.value = responseEsPageVO?.records || [];
        exceptionTotal.value = (total ? total || 0 : responseEsPageVO?.total || 0);
        console.log(exceptionTotal.value, 'exception total');

      })
      .finally(() => {
        exceptionLoading.value = false;
      });
  };
  const changeExceptionTable = (pagination, _filters, sorter) => {
    const params = cloneDeep(exceptionListParams);
    if (sorter.field) {
      params.orderFiled = sorter.field;
      switch (sorter.order) {
        case "descend":
          params.isDesc = true;
          break;
        case "ascend":
          params.isDesc = false;
          break;
        default:
          delete params.isDesc;
          delete params.orderFiled;
          break;
      }
    }
    const { current, pageSize: size } = pagination;
    if (current !== page) {
      params.startPage = current;
      setPage(current);
    }
    if (size !== pageSize) {
      params.size = size;
      setPageSize(size);
    }
    setExceptionListParams(params);
    getExceptionData(params, allDataExceptCount.current);
  };
  const searchExceptionList = (
    url,
    type,
    record
  ) => {
    const listParams = {
      ...exceptionListParams.value,
      startPage: 1,
      contentKey: url,
      exceptionClass: type ? [type] : [],
    };
    // 先删除dstIP和dstPort
    delete listParams.dstIP;
    delete listParams.dstPort;
    // 先重置请求参数srcWorkloadList为初始值（不从全量列表跳转的src参数为当前详情统计的源端数据）
    if (pageType.value === "node") {
      if (srcNodes.value.length) {
        listParams.srcWorkloadList = map(srcNodes.value, (node) => {
          return {
            masterIp: node.masterIp,
            namespace: node.namespace,
            workloadKind: node.workloadKind,
            workloadName: node.workloadName,
          };
        });
      } else {
        delete listParams.srcWorkloadList;
      }
    } else {
      const {
        masterIp: srcMasterIp,
        namespace: srcNamespace,
        workloadKind: srcWorkloadKind,
        workloadName: srcWorkloadName,
      } = handleWorkloadKey(nodeInfo.value.srcWorkloadKey || "");
      listParams.srcWorkloadList = [
        {
          masterIp: srcMasterIp,
          namespace: srcNamespace,
          workloadKind: srcWorkloadKind,
          workloadName: srcWorkloadName,
        },
      ];
    }
    // 存在fullData 表示是从全量列表跳转过来的
    if (record) {
      // 当前url不存在，则需要把dstIp和dstPort传给后台
      if (!url) {
        listParams.dstIP = record.dstIp;
        listParams.dstPort = record.dstPort;
      }
      listParams.srcWorkloadList = [
        {
          masterIp: record.srcMasterIp,
          namespace: record.srcNamespace,
          workloadKind: record.srcWorkloadKind,
          workloadName: record.srcWorkload,
        },
      ];
    }
    // setRadioValue("exception");
    // setExceptionType(type);
    exceptionListParams.startPage = (1);
    // setExceptionListParams(listParams);
    exceptionListParams.value = listParams
    console.log(type, "type");
    const params = record
      ? [listParams, type === 3 ? record.errorCount : record.slowCount]
      : [listParams, allDataExceptCount.current];
    getExceptionData(...params);
  };
  // watch([() => node, () => queryTime, () => pageType], ([node, queryTime]) => {
  //   if (node && queryTime.from) {
  //     getFullData().then(() => {
  //       const params = buildExceptionParams();
  //     });
  //   }
  // });
  return {
    exceptionList,
    exceptionLoading,
    exceptionListParams,
    exceptionTotal,
    buildExceptionParams,
    getExceptionData,
    changeExceptionTable,
    searchExceptionList
  }
}
